<template>
  <div class="base-container">
    <t-form ref="form" :data="queryParams" label-width="80"
      @submit="() => { this.pagination.current = 1; this.queryParams.pageNum = 1; this.getList() }"
      @reset="() => { this.pagination.current = 1; this.queryParams.pageNum = 1; this.getList() }">
      <t-row style="border-bottom: 1px solid #E5E6EB;margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="专利名称" name="name">
            <t-input v-model="queryParams.name" clearable placeholder="请输入专利名称" style="width: 240px" />
          </t-form-item>
          <t-form-item label="专利号" name="patentNum">
            <t-input v-model="queryParams.patentNum" clearable placeholder="请输入专利号" style="width: 240px" />
          </t-form-item>
          <t-form-item label="专利类型" name="patentType">
            <t-select style="width: 240px" clearable v-model="queryParams.patentType" :options="dict.type.patent_type">
            </t-select>
          </t-form-item>
          <t-form-item label="申请日" name="applyDateRange">
            <t-date-range-picker style="width: 280px" :placeholder="['开始时间', '结束时间']"
              v-model="queryParams.applyDateRange" allow-input clearable />
          </t-form-item>
          <t-form-item label="授权公告日" name="authorizationDateRange">
            <t-date-range-picker style="width: 280px" :placeholder="['开始时间', '结束时间']"
              v-model="queryParams.authorizationDateRange" allow-input clearable />
          </t-form-item>
          <t-form-item label="专利阶段" name="phaseType">
            <t-select style="width: 240px" clearable v-model="queryParams.phaseType"
              :options="dict.type.patent_phase_type">
            </t-select>
          </t-form-item>
          <t-form-item label="填报单位" name="declareDeptName">
            <t-input v-model="queryParams.declareDeptName" clearable placeholder="请输入填报单位" style="width: 240px" />
          </t-form-item>
          <t-form-item label="参与人员" name="peopleName">
            <t-input v-model="queryParams.peopleName" clearable style="width: 240px" />
          </t-form-item>
          <t-form-item label="专利状态" name="patentState">
            <t-select style="width: 240px" clearable multiple v-model="queryParams.projectStatuss"
              :options="dict.type.patent_state">
            </t-select>
          </t-form-item>
          <t-form-item label="子系统名称" name="serviceCode">
            <t-select clearable v-model="queryParams.serviceCode" :keys="{ label: 'serviceName', value: 'serviceCode' }"
              style="width: 240px" :options="serviceOptions"></t-select>
          </t-form-item>
          <t-form-item label="项目名称" name="businessId">
            <t-select :disabled="queryParams.serviceCode === ''" @search="remoteProject" placeholder="请先选择子系统后搜索"
              v-model="queryParams.businessId" style="width: 240px" filterable clearable
              :keys="{ label: 'businessName', value: 'businessId' }" :options="projectOptions">
            </t-select>
          </t-form-item>
          <t-form-item label="外部项目名称" name="businessName">
            <t-input v-model="queryParams.businessName" clearable style="width: 240px" />
          </t-form-item>
        </t-col>

        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit">查询</t-button>
          <t-button theme="default" variant="outline" type="reset">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <!-- <div class="btn-group-inline">
      <t-button @click="apply" variant="outline" theme="primary">
        <t-icon name="add" slot="icon"/>
        录入
      </t-button>
    </div> -->
    <t-table rowKey="id" :data="data" :columns="columns" hover :pagination="pagination" :loading="dataLoading">
      <template #name="{ row }">
        <t-link @click="dialog.objId = row.id; dialog.header = row.name; dialog.open_review = true" hover="color"
          theme="primary">{{ row.name }}</t-link>
      </template>
      <template #patentMemberList="{ row }">
        <template v-for="(item, index) in row.patentMemberList">
          {{ item.name }}{{ index + 1 === row.patentMemberList.length ? '' : '、' }}
        </template>
      </template>
      <template #patentRightList="{ row }">
        <template v-for="(item, index) in row.patentRightList">
          {{ item.company }}{{ index + 1 === row.patentRightList.length ? '' : '、' }}
        </template>
      </template>
      <template #patentProjectList="{ row }">
        <template v-for="(item, index) in row.patentProjectList">
          {{ item.businessName }}{{ index + 1 === row.patentProjectList.length ? '' : '、' }}
        </template>
      </template>
      <template #patentType="{ row }">
        {{ row.patentType | filterByDict(dict.type.patent_type) }}
      </template>
      <!-- <template #patentState="{ row }">
        {{ row.patentState | filterByDict(dict.type.patent_state) }}
      </template> -->
      <template #patentState="{ row }">
        <t-tag @click="dialog.header = row.name; dialog.objId = row.id; dialog.open_approve_list = true"
          class="cursor-pointer" :theme="handleTheme(row.patentState, dict.type.achievement_status)" variant="light">
          {{ row.patentState | filterByDict(dict.type.patent_state) }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <!--        v-if="['1','4',null].includes(row.patentStatus)"-->
        <t-button @click="updateData(row)" size="small" variant="text" class="t-button-link"
          v-if="row.createUserId === Number($store.state.user.userId)">
          <t-icon name="edit-1" slot="icon" />
          继续录入
        </t-button>
        <t-button size="small" @click="dialog.objId = row.id; dialog.header = row.name; dialog.open_detail = true"
          variant="text" class="t-button-link">
          <t-icon name="info-circle" slot="icon" />
          详情
        </t-button>
        <!--        ['1','4',null].includes(row.patentStatus)  &&-->
        <t-button v-if="row.createUserId === Number($store.state.user.userId)" theme="danger" @click="delObj(row)"
          size="small" variant="text" class="t-button-link">
          <t-icon name="delete" slot="icon" />
          删除
        </t-button>
      </template>
      <template #phaseType="{ row }">
        {{ row.phaseType | filterByDict(dict.type.patent_phase_type) }}
      </template>
      <template #patentStatus="{ row }">
        <t-tag @click="dialog.header = row.name; dialog.objId = row.id; dialog.open_approve_list = true"
          class="cursor-pointer" :theme="handleTheme(row.patentStatus, dict.type.achievement_status)" variant="light">
          {{ row.patentStatus | filterByDict(dict.type.achievement_status) }}
        </t-tag>
      </template>
    </t-table>
    <patent-detail-dialog :objId="dialog.objId" :header="dialog.header" :visible.sync="dialog.open_detail"
      v-if="dialog.open_detail">
    </patent-detail-dialog>
    <file-review :header="dialog.header" achievementType="2" :visible.sync="dialog.open_review"
      v-if="dialog.open_review" :objId="dialog.objId"></file-review>

  </div>
</template>

<script>
import PatentDetailDialog from "./components/patent-detail-dialog.vue";
import PatentDetail from "./components/patent-detail.vue";
import fileReview from "../components/file-review.vue";

export default {
  name: "patent-my",
  dicts: ['patent_type', 'achievement_status', "patent_phase_type", "patent_state"],
  components: {
    PatentDetailDialog,
    fileReview
  },
  data () {
    return {
      serviceOptions: [],
      projectOptions: [],
      dialog: {
        header: "",
        open: false,
        objId: null,
        open_approve_list: false,
        open_detail: false,
        open_review: false,
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        patentNum: '',
        patentType: '',
        projectStatuss: [],
        applyDate: '',
        startApplyDate: '',
        applyDateRange: [],
        endApplyDate: '',
        startAuthorizationDate: '',
        endAuthorizationDate: '',
        authorizationDateRange: [],
        inventor: '',
        righter: '',
        authorizationDate: '',
        phaseType: '',
        declareDeptName: '',
        patentStatus: '',
        peopleName: '',
        businessName: '',
        status: "",
        dateRange: [],
        serviceCode: '',
        businessId: null
      },
      data: [],
      columns: [
        {
          colKey: "name",
          title: "专利名称",
          align: "center"
        },
        {
          colKey: "patentNum",
          title: "专利号",
          align: "center"
        },
        {
          colKey: "patentType",
          title: "专利类型",
          align: "center"
        },
        {
          colKey: "applyDate",
          title: "申请日",
          align: "center"
        },
        {
          colKey: "authorizationDate",
          title: "授权公告日",
          align: "center"
        },
        {
          colKey: 'authorizationNum',
          title: '授权公告号',
          align: 'center',
        },
        {
          colKey: "phaseType",
          title: "专利阶段",
          align: "center"
        },
        // {
        //   colKey: "declareDeptName",
        //   title: "填报单位",
        //   align: "center"
        // },
        {
          colKey: "patentMemberList",
          title: "专利发明人",
          align: "center"
        },
        {
          colKey: "patentRightList",
          title: "专利权人",
          align: "center"
        },
        {
          colKey: "declareDeptName",
          title: "填报单位",
          align: "center"
        },
        {
          colKey: "patentProjectList",
          title: "项目来源",
          align: "center"
        },
        // {
        //   colKey: "createTime",
        //   title: "创建时间",
        //   align: "center"
        // },
        {
          colKey: "patentState",
          title: "专利状态",
          align: "center",
          fixed: 'right'
        },
        {
          colKey: "op",
          title: "操作",
          align: "center",
          width: 140,
          fixed: 'right'
        }
      ],
      dataLoading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination, pageInfo)
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList()
        },
      },
    };
  },
  created () {
    Object.assign(this.queryParams, this.handelQuery(this.queryParams, this.$route.query))
    if (this.queryParams.businessId) {
      this.remoteProject(this.queryParams.projectName)
    }
    this.getSysServices();
    this.getList();
  },
  methods: {
    remoteProject (search) {
      this.$api.cgzh.getProjectByServiceCode({
        serviceCode: this.queryParams.serviceCode,
        // businessId: this.queryParams.businessId,
        projectName: search,
      }).then(response => {
        response.data.forEach(val2 => {
          const index = this.projectOptions.findIndex(val => val.businessId === val2.businessId)
          if (index === -1) {
            this.projectOptions.push(val2);
          }
        })
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getSysServices () {
      this.$api.cgzh.getSysServices().then(response => {
        this.serviceOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getList () {
      this.dataLoading = true;
      [this.queryParams.startApplyDate, this.queryParams.endApplyDate] = this.queryParams.applyDateRange;
      [this.queryParams.startAuthorizationDate, this.queryParams.endAuthorizationDate] = this.queryParams.authorizationDateRange;
      this.$api.cgzh.patent.myList(this.queryParams).then(response => {
        this.data = response.rows;
        this.pagination.total = response.total;
        this.dataLoading = false;
      }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    apply () {
      this.$router.push(`/cgzh/other/patent/patent-apply/${Date.parse(new Date())}`);
    },
    updateData (row) {
      sessionStorage.removeItem(`${row.id}-patent-activeForm`)
      const taskId = row.id;
      const activeFormList = [];
      this.$api.cgzh.patent.getAll(row.id).then(response => {
        sessionStorage.removeItem(`${taskId}-patent-patentId`);
        if (response.data.id) {
          sessionStorage.setItem(`${taskId}-patent-patentId`, response.data.id)
        } else {
          activeFormList.push(0);
        }
        if (response.data.patentMemberList && response.data.patentMemberList.length > 0) {
          sessionStorage.setItem(`${taskId}-patent-memberId`, response.data.patentMemberList.length)
        } else {
          activeFormList.push(1);
        }
        if (response.data.patentRightList && response.data.patentRightList.length > 0) {
          sessionStorage.setItem(`${taskId}-patent-companyId`, response.data.patentRightList.length)
        } else {
          activeFormList.push(2);
        }
        if (response.data.patentBenefitList && response.data.patentBenefitList.length > 0) {
          sessionStorage.setItem(`${taskId}-patent-benefitId`, response.data.patentBenefitList.length)
        } else {
          activeFormList.push(3);
        }
        if (response.data.patentProjectList && response.data.patentProjectList.length > 0) {
          sessionStorage.setItem(`${taskId}-patent-projectId`, response.data.patentProjectList.length)
        } else {
          activeFormList.push(4);
        }
        if (activeFormList.length <= 0) {
          sessionStorage.setItem(`${taskId}-patent-activeForm`, 5); // 跳转到最后一步
        } else {
          sessionStorage.setItem(`${taskId}-patent-activeForm`, activeFormList[0]); // 跳转到第一个不满足
        }
        this.$router.push({ path: `/cgzh/other/patent/patent-apply/${row.id}`, query: { title: `专利录入-${row.name}` } });
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    delObj (row) {
      const confirmDia = this.$dialog.confirm({
        header: "系统提示",
        body: `是否确认删除专利名称为"${row.name}"的数据项？`,
        theme: "warning",
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          this.$api.cgzh.patent.delete(row.id).then(
            (res) => {
              this.getList();
              this.$message.success("删除成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        }
      });
    }
  }
};
</script>

<style scoped></style>
